Project: Identify Customer Segments

In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.

This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.

It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.

At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.

In [1]:
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from collections import Counter
# magic word for producing visualizations in notebook
%matplotlib inline
'''
Import note: The classroom currently uses sklearn version 0.19.
If you need to use an imputer, it is available in sklearn.preprocessing.Imputer,
instead of sklearn.impute as in newer versions of sklearn.
'''
Out[1]:
'\nImport note: The classroom currently uses sklearn version 0.19.\nIf you need to use an imputer, it is available in sklearn.preprocessing.Imputer,\ninstead of sklearn.impute as in newer versions of sklearn.\n'

Step 0: Load the Data

There are four files associated with this project (not including this one):

  • Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).
  • Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).
  • Data_Dictionary.md: Detailed information file about the features in the provided datasets.
  • AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columns

Each row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.

To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.

Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.

In [3]:
# Load in the general demographics data.
azdias = pd.DataFrame(pd.read_csv('./Udacity_AZDIAS_Subset.csv', delimiter = ';'))
# Load in the feature summary file.
feat_info = pd.DataFrame(pd.read_csv('./AZDIAS_Feature_Summary.csv', delimiter = ';'))
In [11]:
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
azdias.head()
Out[11]:
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 -1 2 1 2.0 3 4 3 5 5 3 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 -1 1 2 5.0 1 5 2 5 4 5 ... 2.0 3.0 2.0 1.0 1.0 5.0 4.0 3.0 5.0 4.0
2 -1 3 2 3.0 1 4 1 2 3 5 ... 3.0 3.0 1.0 0.0 1.0 4.0 4.0 3.0 5.0 2.0
3 2 4 2 2.0 4 2 5 2 1 2 ... 2.0 2.0 2.0 0.0 1.0 3.0 4.0 2.0 3.0 3.0
4 -1 3 1 5.0 4 3 4 1 3 2 ... 2.0 4.0 2.0 1.0 2.0 3.0 3.0 4.0 6.0 5.0

5 rows × 85 columns

In [12]:
azdias.shape
Out[12]:
(891221, 85)
In [14]:
azdias.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891221 entries, 0 to 891220
Data columns (total 85 columns):
AGER_TYP                 891221 non-null int64
ALTERSKATEGORIE_GROB     891221 non-null int64
ANREDE_KZ                891221 non-null int64
CJT_GESAMTTYP            886367 non-null float64
FINANZ_MINIMALIST        891221 non-null int64
FINANZ_SPARER            891221 non-null int64
FINANZ_VORSORGER         891221 non-null int64
FINANZ_ANLEGER           891221 non-null int64
FINANZ_UNAUFFAELLIGER    891221 non-null int64
FINANZ_HAUSBAUER         891221 non-null int64
FINANZTYP                891221 non-null int64
GEBURTSJAHR              891221 non-null int64
GFK_URLAUBERTYP          886367 non-null float64
GREEN_AVANTGARDE         891221 non-null int64
HEALTH_TYP               891221 non-null int64
LP_LEBENSPHASE_FEIN      886367 non-null float64
LP_LEBENSPHASE_GROB      886367 non-null float64
LP_FAMILIE_FEIN          886367 non-null float64
LP_FAMILIE_GROB          886367 non-null float64
LP_STATUS_FEIN           886367 non-null float64
LP_STATUS_GROB           886367 non-null float64
NATIONALITAET_KZ         891221 non-null int64
PRAEGENDE_JUGENDJAHRE    891221 non-null int64
RETOURTYP_BK_S           886367 non-null float64
SEMIO_SOZ                891221 non-null int64
SEMIO_FAM                891221 non-null int64
SEMIO_REL                891221 non-null int64
SEMIO_MAT                891221 non-null int64
SEMIO_VERT               891221 non-null int64
SEMIO_LUST               891221 non-null int64
SEMIO_ERL                891221 non-null int64
SEMIO_KULT               891221 non-null int64
SEMIO_RAT                891221 non-null int64
SEMIO_KRIT               891221 non-null int64
SEMIO_DOM                891221 non-null int64
SEMIO_KAEM               891221 non-null int64
SEMIO_PFLICHT            891221 non-null int64
SEMIO_TRADV              891221 non-null int64
SHOPPER_TYP              891221 non-null int64
SOHO_KZ                  817722 non-null float64
TITEL_KZ                 817722 non-null float64
VERS_TYP                 891221 non-null int64
ZABEOTYP                 891221 non-null int64
ALTER_HH                 817722 non-null float64
ANZ_PERSONEN             817722 non-null float64
ANZ_TITEL                817722 non-null float64
HH_EINKOMMEN_SCORE       872873 non-null float64
KK_KUNDENTYP             306609 non-null float64
W_KEIT_KIND_HH           783619 non-null float64
WOHNDAUER_2008           817722 non-null float64
ANZ_HAUSHALTE_AKTIV      798073 non-null float64
ANZ_HH_TITEL             794213 non-null float64
GEBAEUDETYP              798073 non-null float64
KONSUMNAEHE              817252 non-null float64
MIN_GEBAEUDEJAHR         798073 non-null float64
OST_WEST_KZ              798073 non-null object
WOHNLAGE                 798073 non-null float64
CAMEO_DEUG_2015          792242 non-null object
CAMEO_DEU_2015           792242 non-null object
CAMEO_INTL_2015          792242 non-null object
KBA05_ANTG1              757897 non-null float64
KBA05_ANTG2              757897 non-null float64
KBA05_ANTG3              757897 non-null float64
KBA05_ANTG4              757897 non-null float64
KBA05_BAUMAX             757897 non-null float64
KBA05_GBZ                757897 non-null float64
BALLRAUM                 797481 non-null float64
EWDICHTE                 797481 non-null float64
INNENSTADT               797481 non-null float64
GEBAEUDETYP_RASTER       798066 non-null float64
KKK                      770025 non-null float64
MOBI_REGIO               757897 non-null float64
ONLINE_AFFINITAET        886367 non-null float64
REGIOTYP                 770025 non-null float64
KBA13_ANZAHL_PKW         785421 non-null float64
PLZ8_ANTG1               774706 non-null float64
PLZ8_ANTG2               774706 non-null float64
PLZ8_ANTG3               774706 non-null float64
PLZ8_ANTG4               774706 non-null float64
PLZ8_BAUMAX              774706 non-null float64
PLZ8_HHZ                 774706 non-null float64
PLZ8_GBZ                 774706 non-null float64
ARBEIT                   794005 non-null float64
ORTSGR_KLS9              794005 non-null float64
RELAT_AB                 794005 non-null float64
dtypes: float64(49), int64(32), object(4)
memory usage: 578.0+ MB
In [123]:
feat_info.head()
Out[123]:
attribute information_level type missing_or_unknown
0 AGER_TYP person categorical [-1,0]
1 ALTERSKATEGORIE_GROB person ordinal [-1,0,9]
2 ANREDE_KZ person categorical [-1,0]
3 CJT_GESAMTTYP person categorical [0]
4 FINANZ_MINIMALIST person ordinal [-1]
In [6]:
# To explore the summaries of Azdias dataset
azdias.describe()
Out[6]:
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
count 891221.000000 891221.000000 891221.000000 886367.000000 891221.000000 891221.000000 891221.000000 891221.000000 891221.000000 891221.000000 ... 774706.000000 774706.000000 774706.000000 774706.000000 774706.000000 774706.000000 774706.000000 794005.000000 794005.000000 794005.00000
mean -0.358435 2.777398 1.522098 3.632838 3.074528 2.821039 3.401106 3.033328 2.874167 3.075121 ... 2.253330 2.801858 1.595426 0.699166 1.943913 3.612821 3.381087 3.167854 5.293002 3.07222
std 1.198724 1.068775 0.499512 1.595021 1.321055 1.464749 1.322134 1.529603 1.486731 1.353248 ... 0.972008 0.920309 0.986736 0.727137 1.459654 0.973967 1.111598 1.002376 2.303739 1.36298
min -1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 ... 0.000000 0.000000 0.000000 0.000000 1.000000 1.000000 1.000000 1.000000 0.000000 1.00000
25% -1.000000 2.000000 1.000000 2.000000 2.000000 1.000000 3.000000 2.000000 2.000000 2.000000 ... 1.000000 2.000000 1.000000 0.000000 1.000000 3.000000 3.000000 3.000000 4.000000 2.00000
50% -1.000000 3.000000 2.000000 4.000000 3.000000 3.000000 3.000000 3.000000 3.000000 3.000000 ... 2.000000 3.000000 2.000000 1.000000 1.000000 4.000000 3.000000 3.000000 5.000000 3.00000
75% -1.000000 4.000000 2.000000 5.000000 4.000000 4.000000 5.000000 5.000000 4.000000 4.000000 ... 3.000000 3.000000 2.000000 1.000000 3.000000 4.000000 4.000000 4.000000 7.000000 4.00000
max 3.000000 9.000000 2.000000 6.000000 5.000000 5.000000 5.000000 5.000000 5.000000 5.000000 ... 4.000000 4.000000 3.000000 2.000000 5.000000 5.000000 5.000000 9.000000 9.000000 9.00000

8 rows × 81 columns

In [7]:
# To see the correlation of each pair of features 
plt.figure(figsize=(144,120))
cor = azdias.corr()
sns.heatmap(cor, annot=True, cmap=plt.cm.Reds)
plt.show()

Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut esc --> a (press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, and esc --> b adds a new cell after the active cell. If you need to convert an active cell to a markdown cell, use esc --> m and to convert to a code cell, use esc --> y.

Step 1: Preprocessing

Step 1.1: Assess Missing Data

The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!

Step 1.1.1: Convert Missing Value Codes to NaNs

The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.

As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.

In [15]:
azdias.isnull().sum()
Out[15]:
AGER_TYP                      0
ALTERSKATEGORIE_GROB          0
ANREDE_KZ                     0
CJT_GESAMTTYP              4854
FINANZ_MINIMALIST             0
FINANZ_SPARER                 0
FINANZ_VORSORGER              0
FINANZ_ANLEGER                0
FINANZ_UNAUFFAELLIGER         0
FINANZ_HAUSBAUER              0
FINANZTYP                     0
GEBURTSJAHR                   0
GFK_URLAUBERTYP            4854
GREEN_AVANTGARDE              0
HEALTH_TYP                    0
LP_LEBENSPHASE_FEIN        4854
LP_LEBENSPHASE_GROB        4854
LP_FAMILIE_FEIN            4854
LP_FAMILIE_GROB            4854
LP_STATUS_FEIN             4854
LP_STATUS_GROB             4854
NATIONALITAET_KZ              0
PRAEGENDE_JUGENDJAHRE         0
RETOURTYP_BK_S             4854
SEMIO_SOZ                     0
SEMIO_FAM                     0
SEMIO_REL                     0
SEMIO_MAT                     0
SEMIO_VERT                    0
SEMIO_LUST                    0
                          ...  
OST_WEST_KZ               93148
WOHNLAGE                  93148
CAMEO_DEUG_2015           98979
CAMEO_DEU_2015            98979
CAMEO_INTL_2015           98979
KBA05_ANTG1              133324
KBA05_ANTG2              133324
KBA05_ANTG3              133324
KBA05_ANTG4              133324
KBA05_BAUMAX             133324
KBA05_GBZ                133324
BALLRAUM                  93740
EWDICHTE                  93740
INNENSTADT                93740
GEBAEUDETYP_RASTER        93155
KKK                      121196
MOBI_REGIO               133324
ONLINE_AFFINITAET          4854
REGIOTYP                 121196
KBA13_ANZAHL_PKW         105800
PLZ8_ANTG1               116515
PLZ8_ANTG2               116515
PLZ8_ANTG3               116515
PLZ8_ANTG4               116515
PLZ8_BAUMAX              116515
PLZ8_HHZ                 116515
PLZ8_GBZ                 116515
ARBEIT                    97216
ORTSGR_KLS9               97216
RELAT_AB                  97216
Length: 85, dtype: int64
In [13]:
azdias.isnull().sum().sum()
Out[13]:
4896838
In [4]:
azdias_1 = azdias.copy()
In [5]:
# Identify missing or unknown data values and convert them to NaNs.
for i in range(len(feat_info)):
    mssng = feat_info['missing_or_unknown'][i].strip('[').strip(']').split(',')
    mssng = [int(value) if (value!='X' and value!='XX' and value!='') else value for value in mssng]
    if mssng != ['']:
        azdias_1 = azdias_1.replace({feat_info.iloc[i].attribute: mssng}, np.nan)
In [5]:
azdias.isnull().sum().sum()
Out[5]:
4896838
In [6]:
azdias_1.isnull().sum().sum()
Out[6]:
8373929

Step 1.1.2: Assess Missing Data in Each Column

How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)

For the remaining features, are there any patterns in which columns have, or share, missing data?

In [5]:
azdias_1_isnull = azdias_1.isnull().sum().sort_values(ascending = False)
for i in azdias_1_isnull:
    print(i, i/len(azdias)*100)
889061 99.75763587258379
685843 76.95543529607134
584612 65.59674873011295
476524 53.468668265222654
392318 44.02028228688507
310267 34.81369940789097
158064 17.73566825736826
158064 17.73566825736826
147988 16.60508448521747
133324 14.959701353536328
133324 14.959701353536328
133324 14.959701353536328
133324 14.959701353536328
133324 14.959701353536328
133324 14.959701353536328
116515 13.073637178657146
116515 13.073637178657146
116515 13.073637178657146
116515 13.073637178657146
116515 13.073637178657146
116515 13.073637178657146
116515 13.073637178657146
111196 12.476815514894735
111196 12.476815514894735
111196 12.476815514894735
108315 12.153551139391913
108164 12.136608091595686
105800 11.871354018812394
99611 11.176913470396231
99352 11.147852216229195
99352 11.147852216229195
99352 11.147852216229195
97632 10.954858559212585
97375 10.92602171627464
97375 10.92602171627464
97274 10.91468894920564
97008 10.884842255736793
94572 10.611509378706293
93740 10.518154307405233
93740 10.518154307405233
93740 10.518154307405233
93155 10.452514022896677
93148 10.451728583594866
93148 10.451728583594866
93148 10.451728583594866
93148 10.451728583594866
77792 8.728699166648902
77792 8.728699166648902
73969 8.299737102245123
73499 8.247000463409188
73499 8.247000463409188
73499 8.247000463409188
73499 8.247000463409188
18348 2.0587486156632306
4854 0.5446460529992
4854 0.5446460529992
4854 0.5446460529992
4854 0.5446460529992
4854 0.5446460529992
4854 0.5446460529992
2881 0.32326437550282144
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
0 0.0
In [38]:
# Perform an assessment of how much missing data there is in each column of the
# dataset.
azdias_1.isnull().sum().sort_values(ascending = False)
Out[38]:
TITEL_KZ                 889061
AGER_TYP                 685843
KK_KUNDENTYP             584612
KBA05_BAUMAX             476524
GEBURTSJAHR              392318
ALTER_HH                 310267
REGIOTYP                 158064
KKK                      158064
W_KEIT_KIND_HH           147988
KBA05_ANTG4              133324
KBA05_GBZ                133324
MOBI_REGIO               133324
KBA05_ANTG1              133324
KBA05_ANTG2              133324
KBA05_ANTG3              133324
PLZ8_GBZ                 116515
PLZ8_HHZ                 116515
PLZ8_BAUMAX              116515
PLZ8_ANTG4               116515
PLZ8_ANTG1               116515
PLZ8_ANTG3               116515
PLZ8_ANTG2               116515
SHOPPER_TYP              111196
VERS_TYP                 111196
HEALTH_TYP               111196
NATIONALITAET_KZ         108315
PRAEGENDE_JUGENDJAHRE    108164
KBA13_ANZAHL_PKW         105800
ANZ_HAUSHALTE_AKTIV       99611
CAMEO_INTL_2015           99352
                          ...  
RETOURTYP_BK_S             4854
ONLINE_AFFINITAET          4854
LP_STATUS_FEIN             4854
LP_STATUS_GROB             4854
GFK_URLAUBERTYP            4854
ALTERSKATEGORIE_GROB       2881
FINANZTYP                     0
GREEN_AVANTGARDE              0
FINANZ_HAUSBAUER              0
FINANZ_UNAUFFAELLIGER         0
FINANZ_ANLEGER                0
FINANZ_SPARER                 0
FINANZ_MINIMALIST             0
ANREDE_KZ                     0
FINANZ_VORSORGER              0
SEMIO_FAM                     0
SEMIO_SOZ                     0
SEMIO_REL                     0
SEMIO_MAT                     0
SEMIO_VERT                    0
SEMIO_LUST                    0
SEMIO_ERL                     0
SEMIO_KULT                    0
SEMIO_RAT                     0
SEMIO_KRIT                    0
SEMIO_DOM                     0
SEMIO_KAEM                    0
SEMIO_PFLICHT                 0
SEMIO_TRADV                   0
ZABEOTYP                      0
Length: 85, dtype: int64
In [6]:
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
azdias_1.drop(['TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX'], axis = 1, inplace = True)
In [7]:
azdias_1.head()
Out[7]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 2.0 1 2.0 3 4 3 5 5 3 4 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 1.0 2 5.0 1 5 2 5 4 5 1 ... 2.0 3.0 2.0 1.0 1.0 5.0 4.0 3.0 5.0 4.0
2 3.0 2 3.0 1 4 1 2 3 5 1 ... 3.0 3.0 1.0 0.0 1.0 4.0 4.0 3.0 5.0 2.0
3 4.0 2 2.0 4 2 5 2 1 2 6 ... 2.0 2.0 2.0 0.0 1.0 3.0 4.0 2.0 3.0 3.0
4 3.0 1 5.0 4 3 4 1 3 2 5 ... 2.0 4.0 2.0 1.0 2.0 3.0 3.0 4.0 6.0 5.0

5 rows × 81 columns

Discussion 1.1.2: Assess Missing Data in Each Column

(Double click this cell and replace this text with your own text, reporting your observations regarding the amount of missing data in each column. Are there any patterns in missing values? Which columns were removed from the dataset?)

The AZDIAS dataset has a total of 8,373,929 NaN values out of 891,221 x 85 values. We observed that the top features that has more than 50% of its values as NaN values are TITEL_KZ, AGER_TYP, KK_KUNDENTYP, and KBA05_BAUMAX. We dropped these feature columns from our dataset AZDIAS.

Step 1.1.3: Assess Missing Data in Each Row

Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.

In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.

  • You can use seaborn's countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.
  • To reduce repeated code, you might want to write a function that can perform this comparison, taking as one of its arguments a column to be compared.

Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.

In [7]:
azdias_2 = azdias_1.copy()
In [8]:
azdias_2_more_20 = azdias_2[azdias_2.isnull().sum(axis = 1) >= 20]
azdias_2_less_20 = azdias_2[azdias_2.isnull().sum(axis = 1) < 20]
print(azdias_2_more_20.shape)
print(azdias_2_less_20.shape)
print(azdias_2.shape)
azdias_2_more_20.head()
(94693, 81)
(796528, 81)
(891221, 81)
Out[8]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 2.0 1 2.0 3 4 3 5 5 3 4 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
11 2.0 1 6.0 3 4 3 5 5 3 4 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
14 3.0 1 6.0 3 4 3 5 5 3 4 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
17 2.0 1 6.0 3 4 3 5 5 3 4 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
24 3.0 2 6.0 3 4 3 5 5 3 4 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

5 rows × 81 columns

In [9]:
azdias_2 = azdias_2_less_20
In [28]:
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
sns.distplot(azdias_2['ALTERSKATEGORIE_GROB'].notnull());
In [29]:
sns.distplot(azdias_2_more_20['ALTERSKATEGORIE_GROB'].notnull());
In [30]:
sns.distplot(azdias_2_less_20['ALTERSKATEGORIE_GROB'].notnull());
In [33]:
sns.distplot(azdias_2['CJT_GESAMTTYP'].notnull());
In [34]:
sns.distplot(azdias_2_more_20['CJT_GESAMTTYP'].notnull());
In [35]:
sns.distplot(azdias_2_less_20['CJT_GESAMTTYP'].notnull());
In [36]:
sns.distplot(azdias_3['ARBEIT'].notnull());
In [37]:
sns.distplot(azdias_3_more_20['ARBEIT'].notnull());
In [38]:
sns.distplot(azdias_2_less_20['ARBEIT'].notnull());

Discussion 1.1.3: Assess Missing Data in Each Row

(Double-click this cell and replace this text with your own text, reporting your observations regarding missing data in rows. Are the data with lots of missing values are qualitatively different from data with few or no missing values?)

I have chosen to drop the row that has more than 20 NaN values. When I checked the distribution for ALTERSKATEGORIE_GROB, CJT_GESAMTTYP and ARBEIT features, I found that for the first two there is no difference in distributions, but for the latter, there is a difference.

Step 1.2: Select and Re-Encode Features

Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.

  • For numeric and interval data, these features can be kept without changes.
  • Most of the variables in the dataset are ordinal in nature. While ordinal values may technically be non-linear in spacing, make the simplifying assumption that the ordinal variables can be treated as being interval in nature (that is, kept without any changes).
  • Special handling may be necessary for the remaining two variable types: categorical, and 'mixed'.

In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.

Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!

In [10]:
azdias_3 = azdias_2.copy()   
In [11]:
azdias_3['OST_WEST_KZ'] = azdias_3['OST_WEST_KZ'].map({'W': 1, 'O': 0})
In [12]:
azdias_3['CAMEO_DEU_2015'] = azdias_3['CAMEO_DEU_2015'].map({'1A': 1, '1B': 2, '1C': 3, '1D': 4, '1E': 5,
                                                         '2A': 6, '2B': 7, '2C': 8, '2D': 9,
                                                         '3A': 10, '3B': 11, '3C': 12, '3D': 13,
                                                         '4A': 14, '4B': 15, '4C': 16, '4D': 17, '4E': 18,
                                                         '5A': 19, '5B': 20, '5C': 21, '5D': 22, '5E': 23, '5F': 24,
                                                         '6A': 25, '6B': 26, '6C': 27, '6D': 28, '6E': 29, '6F': 30,
                                                         '7A': 31, '7B': 32, '7C': 33, '7D': 34, '7E': 35,
                                                         '8A': 36, '8B': 37, '8C': 38, '8D': 39,
                                                         '9A': 40, '9B': 41, '9C': 42, '9D': 43, '9E': 44})
In [34]:
azdias_3.shape
Out[34]:
(791896, 85)
In [12]:
azdias.isnull().sum().sum()
Out[12]:
4896838
In [13]:
azdias_2.isnull().sum().sum()
Out[13]:
5737889
In [14]:
azdias_3.isnull().sum().sum()
Out[14]:
1521518
In [16]:
azdias_3.head(2)
Out[16]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
1 1.0 2 5.0 1 5 2 5 4 5 1 ... 2.0 3.0 2.0 1.0 1.0 5.0 4.0 3.0 5.0 4.0
2 3.0 2 3.0 1 4 1 2 3 5 1 ... 3.0 3.0 1.0 0.0 1.0 4.0 4.0 3.0 5.0 2.0

2 rows × 81 columns

In [13]:
azdias_4 = azdias_3.copy()
In [14]:
azdias_4_head = azdias_4.columns
In [31]:
azdias_4_head
Out[31]:
Index(['ALTERSKATEGORIE_GROB', 'ANREDE_KZ', 'CJT_GESAMTTYP',
       'FINANZ_MINIMALIST', 'FINANZ_SPARER', 'FINANZ_VORSORGER',
       'FINANZ_ANLEGER', 'FINANZ_UNAUFFAELLIGER', 'FINANZ_HAUSBAUER',
       'FINANZTYP', 'GEBURTSJAHR', 'GFK_URLAUBERTYP', 'GREEN_AVANTGARDE',
       'HEALTH_TYP', 'LP_LEBENSPHASE_FEIN', 'LP_LEBENSPHASE_GROB',
       'LP_FAMILIE_FEIN', 'LP_FAMILIE_GROB', 'LP_STATUS_FEIN',
       'LP_STATUS_GROB', 'NATIONALITAET_KZ', 'PRAEGENDE_JUGENDJAHRE',
       'RETOURTYP_BK_S', 'SEMIO_SOZ', 'SEMIO_FAM', 'SEMIO_REL', 'SEMIO_MAT',
       'SEMIO_VERT', 'SEMIO_LUST', 'SEMIO_ERL', 'SEMIO_KULT', 'SEMIO_RAT',
       'SEMIO_KRIT', 'SEMIO_DOM', 'SEMIO_KAEM', 'SEMIO_PFLICHT', 'SEMIO_TRADV',
       'SHOPPER_TYP', 'SOHO_KZ', 'VERS_TYP', 'ZABEOTYP', 'ALTER_HH',
       'ANZ_PERSONEN', 'ANZ_TITEL', 'HH_EINKOMMEN_SCORE', 'W_KEIT_KIND_HH',
       'WOHNDAUER_2008', 'ANZ_HAUSHALTE_AKTIV', 'ANZ_HH_TITEL', 'GEBAEUDETYP',
       'KONSUMNAEHE', 'MIN_GEBAEUDEJAHR', 'OST_WEST_KZ', 'WOHNLAGE',
       'CAMEO_DEUG_2015', 'CAMEO_DEU_2015', 'CAMEO_INTL_2015', 'KBA05_ANTG1',
       'KBA05_ANTG2', 'KBA05_ANTG3', 'KBA05_ANTG4', 'KBA05_GBZ', 'BALLRAUM',
       'EWDICHTE', 'INNENSTADT', 'GEBAEUDETYP_RASTER', 'KKK', 'MOBI_REGIO',
       'ONLINE_AFFINITAET', 'REGIOTYP', 'KBA13_ANZAHL_PKW', 'PLZ8_ANTG1',
       'PLZ8_ANTG2', 'PLZ8_ANTG3', 'PLZ8_ANTG4', 'PLZ8_BAUMAX', 'PLZ8_HHZ',
       'PLZ8_GBZ', 'ARBEIT', 'ORTSGR_KLS9', 'RELAT_AB'],
      dtype='object')
In [15]:
imputer = Imputer(missing_values = np.nan, strategy = 'most_frequent', axis = 0)
azdias_4 = imputer.fit_transform(azdias_4)
In [16]:
azdias_4 = pd.DataFrame(azdias_4, columns = azdias_4_head)
In [23]:
azdias_4.shape
Out[23]:
(796528, 81)
In [24]:
azdias_4.head(2)
Out[24]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 1.0 2.0 5.0 1.0 5.0 2.0 5.0 4.0 5.0 1.0 ... 2.0 3.0 2.0 1.0 1.0 5.0 4.0 3.0 5.0 4.0
1 3.0 2.0 3.0 1.0 4.0 1.0 2.0 3.0 5.0 1.0 ... 3.0 3.0 1.0 0.0 1.0 4.0 4.0 3.0 5.0 2.0

2 rows × 81 columns

In [25]:
azdias_4.isnull().sum().sum()
Out[25]:
0
In [26]:
azdias_4.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 796528 entries, 0 to 796527
Data columns (total 81 columns):
ALTERSKATEGORIE_GROB     796528 non-null float64
ANREDE_KZ                796528 non-null float64
CJT_GESAMTTYP            796528 non-null float64
FINANZ_MINIMALIST        796528 non-null float64
FINANZ_SPARER            796528 non-null float64
FINANZ_VORSORGER         796528 non-null float64
FINANZ_ANLEGER           796528 non-null float64
FINANZ_UNAUFFAELLIGER    796528 non-null float64
FINANZ_HAUSBAUER         796528 non-null float64
FINANZTYP                796528 non-null float64
GEBURTSJAHR              796528 non-null float64
GFK_URLAUBERTYP          796528 non-null float64
GREEN_AVANTGARDE         796528 non-null float64
HEALTH_TYP               796528 non-null float64
LP_LEBENSPHASE_FEIN      796528 non-null float64
LP_LEBENSPHASE_GROB      796528 non-null float64
LP_FAMILIE_FEIN          796528 non-null float64
LP_FAMILIE_GROB          796528 non-null float64
LP_STATUS_FEIN           796528 non-null float64
LP_STATUS_GROB           796528 non-null float64
NATIONALITAET_KZ         796528 non-null float64
PRAEGENDE_JUGENDJAHRE    796528 non-null float64
RETOURTYP_BK_S           796528 non-null float64
SEMIO_SOZ                796528 non-null float64
SEMIO_FAM                796528 non-null float64
SEMIO_REL                796528 non-null float64
SEMIO_MAT                796528 non-null float64
SEMIO_VERT               796528 non-null float64
SEMIO_LUST               796528 non-null float64
SEMIO_ERL                796528 non-null float64
SEMIO_KULT               796528 non-null float64
SEMIO_RAT                796528 non-null float64
SEMIO_KRIT               796528 non-null float64
SEMIO_DOM                796528 non-null float64
SEMIO_KAEM               796528 non-null float64
SEMIO_PFLICHT            796528 non-null float64
SEMIO_TRADV              796528 non-null float64
SHOPPER_TYP              796528 non-null float64
SOHO_KZ                  796528 non-null float64
VERS_TYP                 796528 non-null float64
ZABEOTYP                 796528 non-null float64
ALTER_HH                 796528 non-null float64
ANZ_PERSONEN             796528 non-null float64
ANZ_TITEL                796528 non-null float64
HH_EINKOMMEN_SCORE       796528 non-null float64
W_KEIT_KIND_HH           796528 non-null float64
WOHNDAUER_2008           796528 non-null float64
ANZ_HAUSHALTE_AKTIV      796528 non-null float64
ANZ_HH_TITEL             796528 non-null float64
GEBAEUDETYP              796528 non-null float64
KONSUMNAEHE              796528 non-null float64
MIN_GEBAEUDEJAHR         796528 non-null float64
OST_WEST_KZ              796528 non-null float64
WOHNLAGE                 796528 non-null float64
CAMEO_DEUG_2015          796528 non-null float64
CAMEO_DEU_2015           796528 non-null float64
CAMEO_INTL_2015          796528 non-null float64
KBA05_ANTG1              796528 non-null float64
KBA05_ANTG2              796528 non-null float64
KBA05_ANTG3              796528 non-null float64
KBA05_ANTG4              796528 non-null float64
KBA05_GBZ                796528 non-null float64
BALLRAUM                 796528 non-null float64
EWDICHTE                 796528 non-null float64
INNENSTADT               796528 non-null float64
GEBAEUDETYP_RASTER       796528 non-null float64
KKK                      796528 non-null float64
MOBI_REGIO               796528 non-null float64
ONLINE_AFFINITAET        796528 non-null float64
REGIOTYP                 796528 non-null float64
KBA13_ANZAHL_PKW         796528 non-null float64
PLZ8_ANTG1               796528 non-null float64
PLZ8_ANTG2               796528 non-null float64
PLZ8_ANTG3               796528 non-null float64
PLZ8_ANTG4               796528 non-null float64
PLZ8_BAUMAX              796528 non-null float64
PLZ8_HHZ                 796528 non-null float64
PLZ8_GBZ                 796528 non-null float64
ARBEIT                   796528 non-null float64
ORTSGR_KLS9              796528 non-null float64
RELAT_AB                 796528 non-null float64
dtypes: float64(81)
memory usage: 492.2 MB

Step 1.2.1: Re-Encode Categorical Features

For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:

  • For binary (two-level) categoricals that take numeric values, you can keep them without needing to do anything.
  • There is one binary variable that takes on non-numeric values. For this one, you need to re-encode the values as numbers or create a dummy variable.
  • For multi-level categoricals (three or more values), you can choose to encode the values using multiple dummy variables (e.g. via OneHotEncoder), or (to keep things straightforward) just drop them from the analysis. As always, document your choices in the Discussion section.
In [17]:
# Done in the previous cells

Discussion 1.2.1: Re-Encode Categorical Features

(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding categorical features. Which ones did you keep, which did you drop, and what engineering steps did you perform?)

Features 'OST_WEST_KZ' and 'CAMEO_DEU_2015' have been encoded. Missing values have been imputed with the most frequent value (the mode)

Step 1.2.2: Engineer Mixed-Type Features

There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:

  • "PRAEGENDE_JUGENDJAHRE" combines information on three dimensions: generation by decade, movement (mainstream vs. avantgarde), and nation (east vs. west). While there aren't enough levels to disentangle east from west, you should create two new variables to capture the other two dimensions: an interval-type variable for decade, and a binary variable for movement.
  • "CAMEO_INTL_2015" combines information on two axes: wealth and life stage. Break up the two-digit codes by their 'tens'-place and 'ones'-place digits into two new ordinal variables (which, for the purposes of this project, is equivalent to just treating them as their raw numeric values).
  • If you decide to keep or engineer new features around the other mixed-type features, make sure you note your steps in the Discussion section.

Be sure to check Data_Dictionary.md for the details needed to finish these tasks.

In [19]:
azdias_5 = azdias_4.copy()
In [28]:
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
azdias_5.PRAEGENDE_JUGENDJAHRE.value_counts()
Out[28]:
14.0    210991
8.0     141340
10.0     85696
5.0      84630
3.0      53797
15.0     42446
11.0     35686
9.0      33551
6.0      25648
12.0     24429
1.0      20627
4.0      20447
2.0       7479
13.0      5752
7.0       4009
Name: PRAEGENDE_JUGENDJAHRE, dtype: int64
In [39]:
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
azdias_5.CAMEO_INTL_2015.value_counts()
Out[39]:
51.0    139092
41.0     92284
24.0     91058
14.0     62828
43.0     56634
54.0     45361
25.0     39585
22.0     33119
23.0     26622
13.0     26301
45.0     26118
55.0     23924
52.0     20537
31.0     18947
34.0     18504
15.0     16964
44.0     14814
12.0     13223
35.0     10345
32.0     10345
33.0      9923
Name: CAMEO_INTL_2015, dtype: int64
In [20]:
decade_dict = {1:1, 2:1, 3:2, 4:2, 5:3, 6:3, 7:3, 8:4, 9:4, 10:5, 11:5, 12:5, 13:5, 14:6, 15:6}
movement_dict = {1:1 , 2:0 , 3:1 , 4:0 , 5:1  , 6:0 , 7:0 , 8:1 , 9:0 , 10:1 , 11:0 , 12:1 , 13:0 , 14:1 , 15:0}

azdias_5['DECADE'] = azdias_5['PRAEGENDE_JUGENDJAHRE']
azdias_5['MOVEMENT'] = azdias_5['PRAEGENDE_JUGENDJAHRE']

azdias_5["DECADE"].replace(decade_dict, inplace = True)
azdias_5['MOVEMENT'].replace(movement_dict, inplace = True)
In [41]:
azdias_5.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 796528 entries, 0 to 796527
Data columns (total 83 columns):
ALTERSKATEGORIE_GROB     796528 non-null float64
ANREDE_KZ                796528 non-null float64
CJT_GESAMTTYP            796528 non-null float64
FINANZ_MINIMALIST        796528 non-null float64
FINANZ_SPARER            796528 non-null float64
FINANZ_VORSORGER         796528 non-null float64
FINANZ_ANLEGER           796528 non-null float64
FINANZ_UNAUFFAELLIGER    796528 non-null float64
FINANZ_HAUSBAUER         796528 non-null float64
FINANZTYP                796528 non-null float64
GEBURTSJAHR              796528 non-null float64
GFK_URLAUBERTYP          796528 non-null float64
GREEN_AVANTGARDE         796528 non-null float64
HEALTH_TYP               796528 non-null float64
LP_LEBENSPHASE_FEIN      796528 non-null float64
LP_LEBENSPHASE_GROB      796528 non-null float64
LP_FAMILIE_FEIN          796528 non-null float64
LP_FAMILIE_GROB          796528 non-null float64
LP_STATUS_FEIN           796528 non-null float64
LP_STATUS_GROB           796528 non-null float64
NATIONALITAET_KZ         796528 non-null float64
PRAEGENDE_JUGENDJAHRE    796528 non-null float64
RETOURTYP_BK_S           796528 non-null float64
SEMIO_SOZ                796528 non-null float64
SEMIO_FAM                796528 non-null float64
SEMIO_REL                796528 non-null float64
SEMIO_MAT                796528 non-null float64
SEMIO_VERT               796528 non-null float64
SEMIO_LUST               796528 non-null float64
SEMIO_ERL                796528 non-null float64
SEMIO_KULT               796528 non-null float64
SEMIO_RAT                796528 non-null float64
SEMIO_KRIT               796528 non-null float64
SEMIO_DOM                796528 non-null float64
SEMIO_KAEM               796528 non-null float64
SEMIO_PFLICHT            796528 non-null float64
SEMIO_TRADV              796528 non-null float64
SHOPPER_TYP              796528 non-null float64
SOHO_KZ                  796528 non-null float64
VERS_TYP                 796528 non-null float64
ZABEOTYP                 796528 non-null float64
ALTER_HH                 796528 non-null float64
ANZ_PERSONEN             796528 non-null float64
ANZ_TITEL                796528 non-null float64
HH_EINKOMMEN_SCORE       796528 non-null float64
W_KEIT_KIND_HH           796528 non-null float64
WOHNDAUER_2008           796528 non-null float64
ANZ_HAUSHALTE_AKTIV      796528 non-null float64
ANZ_HH_TITEL             796528 non-null float64
GEBAEUDETYP              796528 non-null float64
KONSUMNAEHE              796528 non-null float64
MIN_GEBAEUDEJAHR         796528 non-null float64
OST_WEST_KZ              796528 non-null float64
WOHNLAGE                 796528 non-null float64
CAMEO_DEUG_2015          796528 non-null float64
CAMEO_DEU_2015           796528 non-null float64
CAMEO_INTL_2015          796528 non-null float64
KBA05_ANTG1              796528 non-null float64
KBA05_ANTG2              796528 non-null float64
KBA05_ANTG3              796528 non-null float64
KBA05_ANTG4              796528 non-null float64
KBA05_GBZ                796528 non-null float64
BALLRAUM                 796528 non-null float64
EWDICHTE                 796528 non-null float64
INNENSTADT               796528 non-null float64
GEBAEUDETYP_RASTER       796528 non-null float64
KKK                      796528 non-null float64
MOBI_REGIO               796528 non-null float64
ONLINE_AFFINITAET        796528 non-null float64
REGIOTYP                 796528 non-null float64
KBA13_ANZAHL_PKW         796528 non-null float64
PLZ8_ANTG1               796528 non-null float64
PLZ8_ANTG2               796528 non-null float64
PLZ8_ANTG3               796528 non-null float64
PLZ8_ANTG4               796528 non-null float64
PLZ8_BAUMAX              796528 non-null float64
PLZ8_HHZ                 796528 non-null float64
PLZ8_GBZ                 796528 non-null float64
ARBEIT                   796528 non-null float64
ORTSGR_KLS9              796528 non-null float64
RELAT_AB                 796528 non-null float64
DECADE                   796528 non-null float64
MOVEMENT                 796528 non-null float64
dtypes: float64(83)
memory usage: 504.4 MB
In [21]:
azdias_5.drop(['PRAEGENDE_JUGENDJAHRE'], axis = 1, inplace = True)
In [43]:
azdias_5.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 796528 entries, 0 to 796527
Data columns (total 82 columns):
ALTERSKATEGORIE_GROB     796528 non-null float64
ANREDE_KZ                796528 non-null float64
CJT_GESAMTTYP            796528 non-null float64
FINANZ_MINIMALIST        796528 non-null float64
FINANZ_SPARER            796528 non-null float64
FINANZ_VORSORGER         796528 non-null float64
FINANZ_ANLEGER           796528 non-null float64
FINANZ_UNAUFFAELLIGER    796528 non-null float64
FINANZ_HAUSBAUER         796528 non-null float64
FINANZTYP                796528 non-null float64
GEBURTSJAHR              796528 non-null float64
GFK_URLAUBERTYP          796528 non-null float64
GREEN_AVANTGARDE         796528 non-null float64
HEALTH_TYP               796528 non-null float64
LP_LEBENSPHASE_FEIN      796528 non-null float64
LP_LEBENSPHASE_GROB      796528 non-null float64
LP_FAMILIE_FEIN          796528 non-null float64
LP_FAMILIE_GROB          796528 non-null float64
LP_STATUS_FEIN           796528 non-null float64
LP_STATUS_GROB           796528 non-null float64
NATIONALITAET_KZ         796528 non-null float64
RETOURTYP_BK_S           796528 non-null float64
SEMIO_SOZ                796528 non-null float64
SEMIO_FAM                796528 non-null float64
SEMIO_REL                796528 non-null float64
SEMIO_MAT                796528 non-null float64
SEMIO_VERT               796528 non-null float64
SEMIO_LUST               796528 non-null float64
SEMIO_ERL                796528 non-null float64
SEMIO_KULT               796528 non-null float64
SEMIO_RAT                796528 non-null float64
SEMIO_KRIT               796528 non-null float64
SEMIO_DOM                796528 non-null float64
SEMIO_KAEM               796528 non-null float64
SEMIO_PFLICHT            796528 non-null float64
SEMIO_TRADV              796528 non-null float64
SHOPPER_TYP              796528 non-null float64
SOHO_KZ                  796528 non-null float64
VERS_TYP                 796528 non-null float64
ZABEOTYP                 796528 non-null float64
ALTER_HH                 796528 non-null float64
ANZ_PERSONEN             796528 non-null float64
ANZ_TITEL                796528 non-null float64
HH_EINKOMMEN_SCORE       796528 non-null float64
W_KEIT_KIND_HH           796528 non-null float64
WOHNDAUER_2008           796528 non-null float64
ANZ_HAUSHALTE_AKTIV      796528 non-null float64
ANZ_HH_TITEL             796528 non-null float64
GEBAEUDETYP              796528 non-null float64
KONSUMNAEHE              796528 non-null float64
MIN_GEBAEUDEJAHR         796528 non-null float64
OST_WEST_KZ              796528 non-null float64
WOHNLAGE                 796528 non-null float64
CAMEO_DEUG_2015          796528 non-null float64
CAMEO_DEU_2015           796528 non-null float64
CAMEO_INTL_2015          796528 non-null float64
KBA05_ANTG1              796528 non-null float64
KBA05_ANTG2              796528 non-null float64
KBA05_ANTG3              796528 non-null float64
KBA05_ANTG4              796528 non-null float64
KBA05_GBZ                796528 non-null float64
BALLRAUM                 796528 non-null float64
EWDICHTE                 796528 non-null float64
INNENSTADT               796528 non-null float64
GEBAEUDETYP_RASTER       796528 non-null float64
KKK                      796528 non-null float64
MOBI_REGIO               796528 non-null float64
ONLINE_AFFINITAET        796528 non-null float64
REGIOTYP                 796528 non-null float64
KBA13_ANZAHL_PKW         796528 non-null float64
PLZ8_ANTG1               796528 non-null float64
PLZ8_ANTG2               796528 non-null float64
PLZ8_ANTG3               796528 non-null float64
PLZ8_ANTG4               796528 non-null float64
PLZ8_BAUMAX              796528 non-null float64
PLZ8_HHZ                 796528 non-null float64
PLZ8_GBZ                 796528 non-null float64
ARBEIT                   796528 non-null float64
ORTSGR_KLS9              796528 non-null float64
RELAT_AB                 796528 non-null float64
DECADE                   796528 non-null float64
MOVEMENT                 796528 non-null float64
dtypes: float64(82)
memory usage: 498.3 MB
In [22]:
new_dict = {11:1, 12:1, 13:1, 14:1, 15:1, 21:2, 22:2, 23:2, 24:2, 25:2, 31:3, 32:3, 33:3, 34:3, 35:3, 41:4, 42:4, 43:4, 44:4, 45:4, 51:5, 52:5, 53:5, 54:5, 55:5}

azdias_5['CAMEO_INTL_2015_NEW'] = azdias_5['CAMEO_INTL_2015']   

azdias_5["CAMEO_INTL_2015_NEW"].replace(new_dict, inplace = True)
In [23]:
azdias_5.drop(['CAMEO_INTL_2015'], axis = 1, inplace = True)
In [79]:
azdias_5.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 796528 entries, 0 to 796527
Data columns (total 82 columns):
ALTERSKATEGORIE_GROB     796528 non-null float64
ANREDE_KZ                796528 non-null float64
CJT_GESAMTTYP            796528 non-null float64
FINANZ_MINIMALIST        796528 non-null float64
FINANZ_SPARER            796528 non-null float64
FINANZ_VORSORGER         796528 non-null float64
FINANZ_ANLEGER           796528 non-null float64
FINANZ_UNAUFFAELLIGER    796528 non-null float64
FINANZ_HAUSBAUER         796528 non-null float64
FINANZTYP                796528 non-null float64
GEBURTSJAHR              796528 non-null float64
GFK_URLAUBERTYP          796528 non-null float64
GREEN_AVANTGARDE         796528 non-null float64
HEALTH_TYP               796528 non-null float64
LP_LEBENSPHASE_FEIN      796528 non-null float64
LP_LEBENSPHASE_GROB      796528 non-null float64
LP_FAMILIE_FEIN          796528 non-null float64
LP_FAMILIE_GROB          796528 non-null float64
LP_STATUS_FEIN           796528 non-null float64
LP_STATUS_GROB           796528 non-null float64
NATIONALITAET_KZ         796528 non-null float64
RETOURTYP_BK_S           796528 non-null float64
SEMIO_SOZ                796528 non-null float64
SEMIO_FAM                796528 non-null float64
SEMIO_REL                796528 non-null float64
SEMIO_MAT                796528 non-null float64
SEMIO_VERT               796528 non-null float64
SEMIO_LUST               796528 non-null float64
SEMIO_ERL                796528 non-null float64
SEMIO_KULT               796528 non-null float64
SEMIO_RAT                796528 non-null float64
SEMIO_KRIT               796528 non-null float64
SEMIO_DOM                796528 non-null float64
SEMIO_KAEM               796528 non-null float64
SEMIO_PFLICHT            796528 non-null float64
SEMIO_TRADV              796528 non-null float64
SHOPPER_TYP              796528 non-null float64
SOHO_KZ                  796528 non-null float64
VERS_TYP                 796528 non-null float64
ZABEOTYP                 796528 non-null float64
ALTER_HH                 796528 non-null float64
ANZ_PERSONEN             796528 non-null float64
ANZ_TITEL                796528 non-null float64
HH_EINKOMMEN_SCORE       796528 non-null float64
W_KEIT_KIND_HH           796528 non-null float64
WOHNDAUER_2008           796528 non-null float64
ANZ_HAUSHALTE_AKTIV      796528 non-null float64
ANZ_HH_TITEL             796528 non-null float64
GEBAEUDETYP              796528 non-null float64
KONSUMNAEHE              796528 non-null float64
MIN_GEBAEUDEJAHR         796528 non-null float64
OST_WEST_KZ              796528 non-null float64
WOHNLAGE                 796528 non-null float64
CAMEO_DEUG_2015          796528 non-null float64
CAMEO_DEU_2015           796528 non-null float64
KBA05_ANTG1              796528 non-null float64
KBA05_ANTG2              796528 non-null float64
KBA05_ANTG3              796528 non-null float64
KBA05_ANTG4              796528 non-null float64
KBA05_GBZ                796528 non-null float64
BALLRAUM                 796528 non-null float64
EWDICHTE                 796528 non-null float64
INNENSTADT               796528 non-null float64
GEBAEUDETYP_RASTER       796528 non-null float64
KKK                      796528 non-null float64
MOBI_REGIO               796528 non-null float64
ONLINE_AFFINITAET        796528 non-null float64
REGIOTYP                 796528 non-null float64
KBA13_ANZAHL_PKW         796528 non-null float64
PLZ8_ANTG1               796528 non-null float64
PLZ8_ANTG2               796528 non-null float64
PLZ8_ANTG3               796528 non-null float64
PLZ8_ANTG4               796528 non-null float64
PLZ8_BAUMAX              796528 non-null float64
PLZ8_HHZ                 796528 non-null float64
PLZ8_GBZ                 796528 non-null float64
ARBEIT                   796528 non-null float64
ORTSGR_KLS9              796528 non-null float64
RELAT_AB                 796528 non-null float64
DECADE                   796528 non-null float64
MOVEMENT                 796528 non-null float64
CAMEO_INTL_2015_NEW      796528 non-null float64
dtypes: float64(82)
memory usage: 498.3 MB

Discussion 1.2.2: Engineer Mixed-Type Features

(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding mixed-value features. Which ones did you keep, which did you drop, and what engineering steps did you perform?)

Features 'PRAEGENDE_JUGENDJAHRE' and 'CAMEO_INTL_2015' have been re-engineered because they previously had too many variables that can be grouped to facilitate the analysis and training the model

Step 1.2.3: Complete Feature Selection

In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:

  • All numeric, interval, and ordinal type columns from the original dataset.
  • Binary categorical features (all numerically-encoded).
  • Engineered features from other multi-level categorical features and mixed features.

Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.

In [25]:
features = list(azdias_5.columns)
feat_info_1 = feat_info[feat_info['attribute'].isin(features)]
mixed_features = feat_info_1[feat_info_1["type"] == "mixed"]["attribute"]
for feature in mixed_features:
    azdias_5.drop(feature, axis = 1, inplace = True)
In [26]:
azdias_5.isnull().sum().sum()
Out[26]:
0
In [27]:
azdias_5.head(2)
Out[27]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB DECADE MOVEMENT CAMEO_INTL_2015_NEW
0 1.0 2.0 5.0 1.0 5.0 2.0 5.0 4.0 5.0 1.0 ... 2.0 1.0 5.0 4.0 3.0 5.0 4.0 6.0 1.0 5.0
1 3.0 2.0 3.0 1.0 4.0 1.0 2.0 3.0 5.0 1.0 ... 1.0 0.0 4.0 4.0 3.0 5.0 2.0 6.0 0.0 2.0

2 rows × 78 columns

Step 1.3: Create a Cleaning Function

Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.

In [55]:
def clean_data(df):
    """
    Perform feature trimming, re-encoding, and engineering for demographics
    data
    
    INPUT: Demographics DataFrame
    OUTPUT: Trimmed and cleaned demographics DataFrame
    """
    df_1 = df.copy()
    for i in range(len(feat_info)):
        mssng = feat_info['missing_or_unknown'][i].strip('[').strip(']').split(',')
        mssng = [int(value) if (value!='X' and value!='XX' and value!='') else value for value in mssng]
        if mssng != ['']:
            df_1 = df_1.replace({feat_info.iloc[i].attribute: mssng}, np.nan)
        
    
    df_1.drop(['TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX'], axis = 1, inplace = True)
    
    df_2 = df_1.copy()
    
    df_2[df_2.isnull().sum(axis = 1) < 20]
    
    df_3 = df_2.copy()
    
    df_3['OST_WEST_KZ'] = df_3['OST_WEST_KZ'].map({'W': 1, 'O': 0})
    df_3['CAMEO_DEU_2015'] = df_3['CAMEO_DEU_2015'].map({'1A': 1, '1B': 2, '1C': 3, '1D': 4, '1E': 5,
                                                         '2A': 6, '2B': 7, '2C': 8, '2D': 9,
                                                         '3A': 10, '3B': 11, '3C': 12, '3D': 13,
                                                         '4A': 14, '4B': 15, '4C': 16, '4D': 17, '4E': 18,
                                                         '5A': 19, '5B': 20, '5C': 21, '5D': 22, '5E': 23, '5F': 24,
                                                         '6A': 25, '6B': 26, '6C': 27, '6D': 28, '6E': 29, '6F': 30,
                                                         '7A': 31, '7B': 32, '7C': 33, '7D': 34, '7E': 35,
                                                         '8A': 36, '8B': 37, '8C': 38, '8D': 39,
                                                         '9A': 40, '9B': 41, '9C': 42, '9D': 43, '9E': 44})
     
    df_4 = df_3.copy()
    
    df_4_head = df_4.columns
    imputer = Imputer(missing_values = np.nan, strategy = 'most_frequent', axis = 0)
    df_4 = imputer.fit_transform(df_4)
    df_4 = pd.DataFrame(df_4, columns = df_4_head)
    
    df_5 = df_4.copy()
    
    decade_dict = {1:1, 2:1, 3:2, 4:2, 5:3, 6:3, 7:3, 8:4, 9:4, 10:5, 11:5, 12:5, 13:5, 14:6, 15:6}
    movement_dict = {1:1 , 2:0 , 3:1 , 4:0 , 5:1  , 6:0 , 7:0 , 8:1 , 9:0 , 10:1 , 11:0 , 12:1 , 13:0 , 14:1 , 15:0}
    
    df_5['DECADE'] = df_5['PRAEGENDE_JUGENDJAHRE']
    df_5['MOVEMENT'] = df_5['PRAEGENDE_JUGENDJAHRE']
    
    df_5["DECADE"].replace(decade_dict, inplace = True)
    df_5['MOVEMENT'].replace(movement_dict, inplace = True)
    
    new_dict = {11:1, 12:1, 13:1, 14:1, 15:1, 21:2, 22:2, 23:2, 24:2, 25:2, 31:3, 32:3, 33:3, 34:3, 35:3, 41:4, 42:4, 43:4, 44:4, 45:4, 51:5, 52:5, 53:5, 54:5, 55:5}
    
    df_5['CAMEO_INTL_2015_NEW'] = df_5['CAMEO_INTL_2015']
    df_5["CAMEO_INTL_2015_NEW"].replace(new_dict, inplace = True)
    
    df_5 = df_5.drop(['PRAEGENDE_JUGENDJAHRE', 'CAMEO_INTL_2015'], axis = 1, inplace = True)
    
    features = list(df_5.columns)
    feat_info_1 = feat_info[feat_info['attribute'].isin(features)]
    mixed_features = feat_info_1[feat_info_1["type"] == "mixed"]["attribute"]
    for feature in mixed_features:
        df_5.drop(feature, axis = 1, inplace = True)
    
    return df_5
In [56]:
azdias_6 = azdias.copy()
In [57]:
clean_data(azdias_6)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-57-0ac0170af400> in <module>()
----> 1 clean_data(azdias_6)

<ipython-input-55-dd84301102b4> in clean_data(df)
     59     df_5 = df_5.drop(['PRAEGENDE_JUGENDJAHRE', 'CAMEO_INTL_2015'], axis = 1, inplace = True)
     60 
---> 61     features = list(df_5.columns)
     62     feat_info_1 = feat_info[feat_info['attribute'].isin(features)]
     63     mixed_features = feat_info_1[feat_info_1["type"] == "mixed"]["attribute"]

AttributeError: 'NoneType' object has no attribute 'columns'
In [57]:
azdias_5.head(2)
Out[57]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB DECADE MOVEMENT CAMEO_INTL_2015_NEW
0 1.0 2.0 5.0 1.0 5.0 2.0 5.0 4.0 5.0 1.0 ... 1.0 1.0 5.0 4.0 3.0 5.0 4.0 6.0 1.0 5.0
1 3.0 2.0 3.0 1.0 4.0 1.0 2.0 3.0 5.0 1.0 ... 0.0 1.0 4.0 4.0 3.0 5.0 2.0 6.0 0.0 2.0

2 rows × 82 columns

In [58]:
azdias_6.head(2)
Out[58]:
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 -1 2 1 2.0 3 4 3 5 5 3 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 -1 1 2 5.0 1 5 2 5 4 5 ... 2.0 3.0 2.0 1.0 1.0 5.0 4.0 3.0 5.0 4.0

2 rows × 85 columns

Step 2: Feature Transformation

Step 2.1: Apply Feature Scaling

Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:

  • sklearn requires that data not have missing values in order for its estimators to work properly. So, before applying the scaler to your data, make sure that you've cleaned the DataFrame of the remaining missing values. This can be as simple as just removing all data points with missing data, or applying an Imputer to replace all missing values. You might also try a more complicated procedure where you temporarily remove missing values in order to compute the scaling parameters before re-introducing those missing values and applying imputation. Think about how much missing data you have and what possible effects each approach might have on your analysis, and justify your decision in the discussion section below.
  • For the actual scaling function, a StandardScaler instance is suggested, scaling each feature to mean 0 and standard deviation 1.
  • For these classes, you can make use of the .fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.
In [29]:
azdias_7 = azdias_5.copy()
In [30]:
azdias_7_head = azdias_7.columns
In [31]:
# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
scaler = StandardScaler()
azdias_7 = scaler.fit_transform(azdias_7)
In [32]:
azdias_7 = pd.DataFrame(azdias_7, columns = azdias_7_head)
In [33]:
azdias_7.head(2)
Out[33]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB DECADE MOVEMENT CAMEO_INTL_2015_NEW
0 -1.766269 0.958082 0.974671 -1.494308 1.538111 -1.040683 1.466463 0.960573 1.33814 -1.342965 ... 0.403396 0.440700 1.453841 0.573206 -0.171972 -0.127418 0.684559 1.098924 0.530661 1.176565
1 0.200616 0.958082 -0.329634 -1.494308 0.864762 -1.766886 -0.570882 0.245775 1.33814 -1.342965 ... -0.621889 -0.936455 0.418336 0.573206 -0.171972 -0.127418 -0.789435 1.098924 -1.884442 -0.869064

2 rows × 78 columns

Discussion 2.1: Apply Feature Scaling

(Double-click this cell and replace this text with your own text, reporting your decisions regarding feature scaling.)

All features were standardized using StandardScaler tool.

Step 2.2: Perform Dimensionality Reduction

On your scaled data, you are now ready to apply dimensionality reduction techniques.

  • Use sklearn's PCA class to apply principal component analysis on the data, thus finding the vectors of maximal variance in the data. To start, you should not set any parameters (so all components are computed) or set a number of components that is at least half the number of features (so there's enough features to see the general trend in variability).
  • Check out the ratio of variance explained by each principal component as well as the cumulative variance explained. Try plotting the cumulative or sequential values using matplotlib's plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.
  • Once you've made a choice for the number of components to keep, make sure you re-fit a PCA instance to perform the decided-on transformation.
In [34]:
pca = PCA(n_components = 78)
pca.fit(azdias_7)
Out[34]:
PCA(copy=True, iterated_power='auto', n_components=78, random_state=None,
  svd_solver='auto', tol=0.0, whiten=False)
In [35]:
# Apply PCA to the data.
def screen_plot(pca):
    n_components = len(pca.explained_variance_ratio_)
    index = np.arange(n_components)
    values = pca.explained_variance_ratio_
    
    plt.figure(figsize = (20, 10))
    ax = plt.subplot(111)
    cumvals = np.cumsum(values)
    ax.bar(index, values)
    ax.plot(index, cumvals)
    
    for i in range(n_components):
        ax.annotate(r"%s%%" % ((str(values[i]*100)[:4])), (index[i]+0.2, values[i]), va = 'bottom', ha = 'center', fontsize = 12)
        
    ax.xaxis.set_tick_params(width = 0)
    ax.yaxis.set_tick_params(width = 2, length = 12)
    
    ax.set_xlabel('Principal Component')
    ax.set_ylabel('Variance Explained (%)')
    plt.title('Explained Variance Per Principal Component')   
In [36]:
# Investigate the variance accounted for by each principal component.
screen_plot(pca)
In [37]:
# Re-apply PCA to the data while selecting for number of components to retain.
pca = PCA(n_components = 14)
pca.fit(azdias_7)
pca.transform(azdias_7)
Out[37]:
array([[ 4.64613624, -3.27563626, -2.93658219, ...,  0.65433528,
         0.09945031, -0.71723898],
       [-0.41595411, -0.25343457, -3.45020201, ..., -0.34660202,
        -0.7568642 ,  0.24086258],
       [-4.69506254,  1.90799131, -0.63647582, ...,  0.08045995,
        -0.16727308, -0.1993792 ],
       ..., 
       [-0.2849756 , -3.28971482, -2.68866228, ...,  0.4756664 ,
        -0.24659088,  0.07026854],
       [ 6.13481946, -3.85291131,  2.75456378, ...,  0.7416373 ,
         1.27467278,  0.26528334],
       [ 0.11995778,  1.82092724,  2.97959391, ...,  0.64489514,
        -0.82797269, -0.03518981]])
In [38]:
screen_plot(pca)

Discussion 2.2: Perform Dimensionality Reduction

(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding dimensionality reduction. How many principal components / transformed features are you retaining for the next step of the analysis?)

Step 2.3: Interpret Principal Components

Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.

As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.

  • To investigate the features, you should map each weight to their corresponding feature name, then sort the features according to weight. The most interesting features for each principal component, then, will be those at the beginning and end of the sorted list. Use the data dictionary document to help you understand these most prominent features, their relationships, and what a positive or negative value on the principal component might indicate.
  • You should investigate and interpret feature associations from the first three principal components in this substep. To help facilitate this, you should write a function that you can call at any time to print the sorted list of feature weights, for the i-th principal component. This might come in handy in the next step of the project, when you interpret the tendencies of the discovered clusters.
In [ ]:
# Map weights for the first principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
In [39]:
def pca_results(good_data, pca):
    dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]

    components = pd.DataFrame(np.round(pca.components_, 4), columns = list(good_data.keys()))
    components.index = dimensions

    ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)
    variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
    variance_ratios.index = dimensions

    fig, ax = plt.subplots(figsize = (14,8))

    components.plot(ax = ax, kind = 'bar');
    ax.set_ylabel("Feature Weights")
    ax.set_xticklabels(dimensions, rotation=0)

    for i, ev in enumerate(pca.explained_variance_ratio_):
        ax.text(i-0.40, ax.get_ylim()[1] + 0.05, "Explained Variance\n%.4f"%(ev))

    return pd.concat([variance_ratios, components], axis = 1)
In [40]:
pca_results(azdias_7, pca)
Out[40]:
Explained Variance ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB DECADE MOVEMENT CAMEO_INTL_2015_NEW
Dimension 1 0.1705 -0.0970 0.0150 0.0413 -0.2061 0.1279 -0.0958 0.0640 0.0614 0.1572 ... 0.1960 0.1884 0.0367 -0.1442 0.1238 0.1656 0.1166 0.0899 0.1138 0.1981
Dimension 2 0.1252 0.2466 0.0574 -0.1228 0.0818 -0.2357 0.2285 -0.2068 -0.2270 0.1017 ... 0.0760 0.0741 0.0103 -0.0595 0.0584 0.0716 0.0538 -0.2449 0.0155 0.0700
Dimension 3 0.0812 0.0379 -0.3659 -0.0256 0.1374 -0.0730 0.0674 -0.1572 -0.0752 -0.0472 ... 0.0432 0.0439 0.0028 -0.0382 0.0358 0.0419 0.0298 -0.0803 -0.0388 0.0342
Dimension 4 0.0487 -0.0177 0.0299 0.0738 0.0526 -0.0072 -0.0115 -0.1062 0.0395 -0.0774 ... 0.1469 0.1389 0.0834 -0.0603 0.1019 0.2681 0.1286 0.0247 -0.3213 -0.0604
Dimension 5 0.0380 0.0704 -0.0199 0.0333 0.0290 -0.0173 0.0092 0.0783 -0.1008 -0.0142 ... -0.0042 0.0241 -0.1929 -0.1738 0.0750 -0.0617 0.0256 -0.0002 0.1600 0.1267
Dimension 6 0.0296 0.0627 -0.0294 -0.0010 -0.0858 0.0078 0.0764 -0.0181 0.0360 0.0799 ... 0.0296 0.0077 0.4540 0.3562 -0.2246 -0.0915 -0.1541 -0.0027 0.0631 0.0212
Dimension 7 0.0265 0.0081 0.0074 -0.0138 -0.0150 0.0048 -0.0482 0.0135 -0.0006 -0.0085 ... -0.0824 0.0780 -0.0868 -0.1283 -0.1571 -0.0558 -0.1969 0.0295 0.0078 -0.1159
Dimension 8 0.0228 -0.0620 0.0704 -0.0816 -0.0743 -0.0656 0.0453 -0.0485 -0.1235 0.2387 ... -0.0134 -0.0205 -0.1331 -0.0746 -0.0282 -0.1326 -0.0495 -0.1186 -0.0108 0.0288
Dimension 9 0.0220 0.1234 -0.0719 0.0145 -0.1598 0.1524 -0.0815 0.0992 0.1347 0.1368 ... -0.0633 -0.0247 -0.1749 -0.0999 -0.0654 -0.0206 -0.0157 0.1459 -0.0637 -0.0468
Dimension 10 0.0214 -0.1518 0.0167 -0.0060 0.0096 -0.0678 0.1409 -0.0458 -0.1425 0.0895 ... -0.1450 -0.0157 0.0336 0.0640 -0.0092 0.0810 0.0005 -0.1045 0.0806 -0.0485
Dimension 11 0.0191 -0.0126 -0.0267 0.0483 0.1309 0.0155 -0.1204 0.0744 -0.1358 -0.1652 ... 0.0516 0.0692 0.1836 0.0899 0.1200 -0.1011 0.0306 0.0745 -0.0679 0.2475
Dimension 12 0.0181 0.0432 0.0693 -0.0694 -0.0378 0.0509 -0.0269 0.0750 0.1168 0.0629 ... -0.0288 0.0184 0.0497 0.0334 0.0405 -0.0135 0.0958 0.0060 -0.1873 0.2383
Dimension 13 0.0173 -0.0174 -0.0159 0.0017 0.1007 -0.0398 0.1125 -0.1325 0.0879 -0.2247 ... 0.0055 -0.0495 -0.2618 -0.1741 -0.3967 -0.1186 -0.1349 -0.0034 0.0025 0.1689
Dimension 14 0.0151 -0.0156 -0.0102 0.0322 -0.0163 0.0031 0.0058 0.0294 0.0159 0.0108 ... 0.0172 -0.0633 -0.0004 0.0356 0.1438 -0.0111 0.1510 -0.0119 -0.0319 -0.0632

14 rows × 79 columns

In [ ]:
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
In [ ]:
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.

Discussion 2.3: Interpret Principal Components

(Double-click this cell and replace this text with your own text, reporting your observations from detailed investigation of the first few principal components generated. Can we interpret positive and negative values from them in a meaningful way?)

PCA has been performed over cleaned azdias dataset (azdias_7). Then we have taken the major 14 components as these components has variance expalianed more than 60%.

Step 3: Clustering

Step 3.1: Apply Clustering to General Population

You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.

  • Use sklearn's KMeans class to perform k-means clustering on the PCA-transformed data.
  • Then, compute the average difference from each point to its assigned cluster's center. Hint: The KMeans object's .score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.
  • Perform the above two steps for a number of different cluster counts. You can then see how the average distance decreases with an increasing number of clusters. However, each additional cluster provides a smaller net benefit. Use this fact to select a final number of clusters in which to group the data. Warning: because of the large size of the dataset, it can take a long time for the algorithm to resolve. The more clusters to fit, the longer the algorithm will take. You should test for cluster counts through at least 10 clusters to get the full picture, but you shouldn't need to test for a number of clusters above about 30.
  • Once you've selected a final number of clusters to use, re-fit a KMeans instance to perform the clustering operation. Make sure that you also obtain the cluster assignments for the general demographics data, since you'll be using them in the final Step 3.3.
In [72]:
def get_kmeans_score(data, center):
    '''
    returns the kmeans score regarding SSE for points to centers
    INPUT:
        data - the dataset you want to fit kmeans to
        center - the number of centers you want (the k value)
    OUTPUT:
        score - the SSE score for the kmeans model fit to the data
    '''
    #instantiate kmeans
    kmeans = KMeans(n_clusters=center)

    # Then fit the model to your data using the fit method
    model = kmeans.fit(data)
    
    # Obtain a score related to the model fit
    score = np.abs(model.score(data))
    
    return score

scores = []
centers = list(range(1,15))

for center in centers:
    scores.append(get_kmeans_score(azdias_7, center))
    
plt.plot(centers, scores, linestyle='--', marker='o', color='b');
plt.xlabel('K');
plt.ylabel('SSE');
plt.title('SSE vs. K');
In [41]:
azdias_7 = pca.transform(azdias_7)
In [42]:
kmeans = KMeans(n_clusters = 4)
model = kmeans.fit(azdias_7)
labels_azdias = model.predict(azdias_7)
In [39]:
labels_azdias
Out[39]:
array([3, 0, 1, ..., 0, 3, 2], dtype=int32)
In [40]:
plt.scatter(azdias_7[:,0], azdias_7[:,1], c = labels_azdias, cmap = 'Set1');
In [ ]:
# Over a number of different cluster counts...


    # run k-means clustering on the data and...
    
    
    # compute the average within-cluster distances.
    
    
In [ ]:
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
In [ ]:
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.

Discussion 3.1: Apply Clustering to General Population

(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding clustering. Into how many clusters have you decided to segment the population?)

As seen in the elbow diagram, it seems that 4 clusters is the perfect choice. We've chosen to apply k-means over the principal components of azdias_7 with 4 clusters.

Step 3.2: Apply All Steps to the Customer Data

Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.

  • Don't forget when loading in the customers data, that it is semicolon (;) delimited.
  • Apply the same feature wrangling, selection, and engineering steps to the customer demographics using the clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.)
  • Use the sklearn objects from the general demographics data, and apply their transformations to the customers data. That is, you should not be using a .fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.
In [43]:
# Load in the customer demographics data.
customers = pd.DataFrame(pd.read_csv('./Udacity_CUSTOMERS_Subset.csv', delimiter = ';'))
In [44]:
customers_1 = customers.copy()
In [48]:
customers_1.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 191652 entries, 0 to 191651
Data columns (total 85 columns):
AGER_TYP                 191652 non-null int64
ALTERSKATEGORIE_GROB     191652 non-null int64
ANREDE_KZ                191652 non-null int64
CJT_GESAMTTYP            188439 non-null float64
FINANZ_MINIMALIST        191652 non-null int64
FINANZ_SPARER            191652 non-null int64
FINANZ_VORSORGER         191652 non-null int64
FINANZ_ANLEGER           191652 non-null int64
FINANZ_UNAUFFAELLIGER    191652 non-null int64
FINANZ_HAUSBAUER         191652 non-null int64
FINANZTYP                191652 non-null int64
GEBURTSJAHR              191652 non-null int64
GFK_URLAUBERTYP          188439 non-null float64
GREEN_AVANTGARDE         191652 non-null int64
HEALTH_TYP               191652 non-null int64
LP_LEBENSPHASE_FEIN      188439 non-null float64
LP_LEBENSPHASE_GROB      188439 non-null float64
LP_FAMILIE_FEIN          188439 non-null float64
LP_FAMILIE_GROB          188439 non-null float64
LP_STATUS_FEIN           188439 non-null float64
LP_STATUS_GROB           188439 non-null float64
NATIONALITAET_KZ         191652 non-null int64
PRAEGENDE_JUGENDJAHRE    191652 non-null int64
RETOURTYP_BK_S           188439 non-null float64
SEMIO_SOZ                191652 non-null int64
SEMIO_FAM                191652 non-null int64
SEMIO_REL                191652 non-null int64
SEMIO_MAT                191652 non-null int64
SEMIO_VERT               191652 non-null int64
SEMIO_LUST               191652 non-null int64
SEMIO_ERL                191652 non-null int64
SEMIO_KULT               191652 non-null int64
SEMIO_RAT                191652 non-null int64
SEMIO_KRIT               191652 non-null int64
SEMIO_DOM                191652 non-null int64
SEMIO_KAEM               191652 non-null int64
SEMIO_PFLICHT            191652 non-null int64
SEMIO_TRADV              191652 non-null int64
SHOPPER_TYP              191652 non-null int64
SOHO_KZ                  145056 non-null float64
TITEL_KZ                 145056 non-null float64
VERS_TYP                 191652 non-null int64
ZABEOTYP                 191652 non-null int64
ALTER_HH                 145056 non-null float64
ANZ_PERSONEN             145056 non-null float64
ANZ_TITEL                145056 non-null float64
HH_EINKOMMEN_SCORE       188684 non-null float64
KK_KUNDENTYP             79715 non-null float64
W_KEIT_KIND_HH           137910 non-null float64
WOHNDAUER_2008           145056 non-null float64
ANZ_HAUSHALTE_AKTIV      141725 non-null float64
ANZ_HH_TITEL             139542 non-null float64
GEBAEUDETYP              141725 non-null float64
KONSUMNAEHE              145001 non-null float64
MIN_GEBAEUDEJAHR         141725 non-null float64
OST_WEST_KZ              141725 non-null object
WOHNLAGE                 141725 non-null float64
CAMEO_DEUG_2015          141224 non-null object
CAMEO_DEU_2015           141224 non-null object
CAMEO_INTL_2015          141224 non-null object
KBA05_ANTG1              135672 non-null float64
KBA05_ANTG2              135672 non-null float64
KBA05_ANTG3              135672 non-null float64
KBA05_ANTG4              135672 non-null float64
KBA05_BAUMAX             135672 non-null float64
KBA05_GBZ                135672 non-null float64
BALLRAUM                 141693 non-null float64
EWDICHTE                 141693 non-null float64
INNENSTADT               141693 non-null float64
GEBAEUDETYP_RASTER       141725 non-null float64
KKK                      137392 non-null float64
MOBI_REGIO               135672 non-null float64
ONLINE_AFFINITAET        188439 non-null float64
REGIOTYP                 137392 non-null float64
KBA13_ANZAHL_PKW         140371 non-null float64
PLZ8_ANTG1               138888 non-null float64
PLZ8_ANTG2               138888 non-null float64
PLZ8_ANTG3               138888 non-null float64
PLZ8_ANTG4               138888 non-null float64
PLZ8_BAUMAX              138888 non-null float64
PLZ8_HHZ                 138888 non-null float64
PLZ8_GBZ                 138888 non-null float64
ARBEIT                   141176 non-null float64
ORTSGR_KLS9              141176 non-null float64
RELAT_AB                 141176 non-null float64
dtypes: float64(49), int64(32), object(4)
memory usage: 124.3+ MB
In [49]:
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
customers_2 = clean_data(customers_1)
In [50]:
customers_2.isnull().sum().sum()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-50-b01cd72afc94> in <module>()
----> 1 customers_2.isnull().sum().sum()

AttributeError: 'NoneType' object has no attribute 'isnull'
In [45]:
customers_3 = customers.copy()
In [53]:
customers_3.isnull().sum().sum()
Out[53]:
2252274
In [46]:
for i in range(len(feat_info)):
    mssng_1 = feat_info['missing_or_unknown'][i].strip('[').strip(']').split(',')
    mssng_1 = [int(value) if (value!='X' and value!='XX' and value!='') else value for value in mssng_1]
    if mssng != ['']:
        customers_3 = customers_3.replace({feat_info.iloc[i].attribute: mssng_1}, np.nan)
        
customers_3.drop(['TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX'], axis = 1, inplace = True)
    
customers_4 = customers_3.copy()
    
customers_4[customers_4.isnull().sum(axis = 1) < 20]
    
customers_5 = customers_4.copy()
    
customers_5['OST_WEST_KZ'] = customers_5['OST_WEST_KZ'].map({'W': 1, 'O': 0})
customers_5['CAMEO_DEU_2015'] = customers_5['CAMEO_DEU_2015'].map({'1A': 1, '1B': 2, '1C': 3, '1D': 4, '1E': 5,
                                                         '2A': 6, '2B': 7, '2C': 8, '2D': 9,
                                                         '3A': 10, '3B': 11, '3C': 12, '3D': 13,
                                                         '4A': 14, '4B': 15, '4C': 16, '4D': 17, '4E': 18,
                                                         '5A': 19, '5B': 20, '5C': 21, '5D': 22, '5E': 23, '5F': 24,
                                                         '6A': 25, '6B': 26, '6C': 27, '6D': 28, '6E': 29, '6F': 30,
                                                         '7A': 31, '7B': 32, '7C': 33, '7D': 34, '7E': 35,
                                                         '8A': 36, '8B': 37, '8C': 38, '8D': 39,
                                                         '9A': 40, '9B': 41, '9C': 42, '9D': 43, '9E': 44})
     
customers_6 = customers_5.copy()
    
customers_6_head = customers_6.columns

imputer = Imputer(missing_values = np.nan, strategy = 'most_frequent', axis = 0)
customers_6 = imputer.fit_transform(customers_6)
customers_6 = pd.DataFrame(customers_6, columns = customers_6_head)
    
customers_7 = customers_6.copy()
    
decade_dict = {1:1, 2:1, 3:2, 4:2, 5:3, 6:3, 7:3, 8:4, 9:4, 10:5, 11:5, 12:5, 13:5, 14:6, 15:6}
movement_dict = {1:1 , 2:0 , 3:1 , 4:0 , 5:1  , 6:0 , 7:0 , 8:1 , 9:0 , 10:1 , 11:0 , 12:1 , 13:0 , 14:1 , 15:0}
    
customers_7['DECADE'] = customers_7['PRAEGENDE_JUGENDJAHRE']
customers_7['MOVEMENT'] = customers_7['PRAEGENDE_JUGENDJAHRE']
    
customers_7["DECADE"].replace(decade_dict, inplace = True)
customers_7['MOVEMENT'].replace(movement_dict, inplace = True)
    
new_dict = {11:1, 12:1, 13:1, 14:1, 15:1, 21:2, 22:2, 23:2, 24:2, 25:2, 31:3, 32:3, 33:3, 34:3, 35:3, 41:4, 42:4, 43:4, 44:4, 45:4, 51:5, 52:5, 53:5, 54:5, 55:5}
    
customers_7['CAMEO_INTL_2015_NEW'] = customers_7['CAMEO_INTL_2015']
customers_7["CAMEO_INTL_2015_NEW"].replace(new_dict, inplace = True)
    
customer_7 = customers_7.drop(['PRAEGENDE_JUGENDJAHRE', 'CAMEO_INTL_2015'], axis = 1, inplace = True)

features = list(customers_7.columns)
feat_info_1 = feat_info[feat_info['attribute'].isin(features)]
mixed_features = feat_info_1[feat_info_1["type"] == "mixed"]["attribute"]
for feature in mixed_features:
    customers_7.drop(feature, axis = 1, inplace = True)
In [47]:
customers_7.isnull().sum().sum()
Out[47]:
0
In [48]:
customers_7.head(2)
Out[48]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB DECADE MOVEMENT CAMEO_INTL_2015_NEW
0 4.0 1.0 5.0 5.0 1.0 5.0 1.0 2.0 2.0 2.0 ... 1.0 0.0 5.0 5.0 1.0 2.0 1.0 2.0 0.0 1.0
1 4.0 1.0 6.0 5.0 1.0 5.0 1.0 3.0 2.0 2.0 ... 1.0 0.0 3.0 3.0 3.0 5.0 3.0 2.0 0.0 1.0

2 rows × 78 columns

In [49]:
customers_8 = customers_7.copy()
In [50]:
customers_8_head = customers_8.columns
scaler_1 = StandardScaler()
customers_8 = scaler_1.fit_transform(customers_8)
customers_8 = pd.DataFrame(customers_8, columns = customers_8_head)
In [51]:
customers_9 = customers_8.copy()
In [52]:
customers_9 = pca.transform(customers_9)
In [51]:
screen_plot(pca)
In [53]:
kmeans = KMeans(n_clusters = 4)
model = kmeans.fit(customers_9)
labels_customers = model.predict(customers_9)
In [53]:
plt.scatter(customers_9[:,0], customers_9[:,1], c = labels, cmap = 'Set1');

Step 3.3: Compare Customer Data to Demographics Data

At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.

Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.

Take a look at the following points in this step:

  • Compute the proportion of data points in each cluster for the general population and the customer data. Visualizations will be useful here: both for the individual dataset proportions, but also to visualize the ratios in cluster representation between groups. Seaborn's countplot() or barplot() function could be handy.
    • Recall the analysis you performed in step 1.1.3 of the project, where you separated out certain data points from the dataset if they had more than a specified threshold of missing values. If you found that this group was qualitatively different from the main bulk of the data, you should treat this as an additional data cluster in this analysis. Make sure that you account for the number of data points in this subset, for both the general population and customer datasets, when making your computations!
  • Which cluster or clusters are overrepresented in the customer dataset compared to the general population? Select at least one such cluster and infer what kind of people might be represented by that cluster. Use the principal component interpretations from step 2.3 or look at additional components to help you make this inference. Alternatively, you can use the .inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.
  • Perform a similar investigation for the underrepresented clusters. Which cluster or clusters are underrepresented in the customer dataset compared to the general population, and what kinds of people are typified by these clusters?
In [54]:
figure, axs = plt.subplots(nrows = 1, ncols = 2, figsize = (10,5))
figure.subplots_adjust(hspace = 1, wspace = .3)

sns.countplot(labels_customers, ax = axs[0])
axs[0].set_title('Customer Clusters')
sns.countplot(labels_azdias, ax = axs[1])
axs[1].set_title('General Clusters')
Out[54]:
Text(0.5,1,'General Clusters')

Discussion 3.3: Compare Customer Data to Demographics Data

(Double-click this cell and replace this text with your own text, reporting findings and conclusions from the clustering analysis. Can we describe segments of the population that are relatively popular with the mail-order company, or relatively unpopular with the company?)

From the diagrams of comparison, it could be seen that cluster 2 is overpresented in the general public demographic data compared to the customers demographic data.

Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.

In [ ]: